import java.util.*;

class TreeNode {
     int val;TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
//前序遍历
class solution {
    List<Integer> list = new ArrayList<>();
    public List<Integer> preorderTraversal(TreeNode root) {
        if(root==null){
            return list;
        }else{
            list.add(root.val);
        }
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        return list;
    }
}

//非递归前序遍历
class SolutionB {
    List<Integer> Tree = new ArrayList<Integer>();
    Stack<TreeNode> stack = new Stack<TreeNode>();
    public List<Integer> preorderTraversal(TreeNode root) {
        while(root!=null||!stack.isEmpty()){
            while(root!=null){
                Tree.add(root.val);
                stack.push(root);
                root = root.left;
            }
            TreeNode cur = stack.pop();
            if(cur.right!=null){
                root = cur.right;
            }
        }
        return Tree;
    }


}